package tech.aistar.controller;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;
import tech.aistar.entity.SeeRoomTrend;
import tech.aistar.service.ISeeRoomTrendService;

import java.io.IOException;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;




@Component
public class SeeRoomController {
    @Autowired
    private ISeeRoomTrendService seeRoomTrendService;
     @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "test01"), exchange = @Exchange(value = "j08_exch",type = "fanout")))
     @RabbitHandler
     public void handlerOrder(@Payload Map<String,Object> maps, @Headers Map<String,Object> headers, Channel channel){
         String house_id = (String) maps.get("house_id");

         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
         ParsePosition pos = new ParsePosition(0);
         try {
             Date date = sdf.parse(sdf.format(new Date()));
             SeeRoomTrend seeRoomTrend = seeRoomTrendService.selectByHouseId(Integer.valueOf(house_id),date);
             if(seeRoomTrend==null) {//没有人看过
                 seeRoomTrendService.insert(new SeeRoomTrend(Integer.valueOf(house_id), 1,sdf.parse(sdf.format(new Date()),pos)));
             }else if(!sdf.format(seeRoomTrend.getSeeTime()).equals(sdf.format(date))){//不是同一天

                 seeRoomTrendService.insert(new SeeRoomTrend(Integer.valueOf(house_id), 1,sdf.parse(sdf.format(new Date()),pos)));
             } else{
                 seeRoomTrendService.updateByHouseId(seeRoomTrend.getSeeCount()+1,sdf.parse(sdf.format(new Date()),pos),Integer.valueOf(house_id));
             }

         } catch (ParseException e) {
             e.printStackTrace();
         }
         long tag = (long) headers.get(AmqpHeaders.DELIVERY_TAG);
         try {
             channel.basicAck(tag,false);
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
}
